<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use fast\Tree;

/**
 * 导航管理
 *
 * @icon   fa fa-dedent
 * @remark
 */
class Navigation extends Backend
{

    /**
     * @var \app\common\model\Navigation
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Navigation');

        $tree = Tree::instance();
        $tree->init(collection($this->model->order('sort desc,id asc')->select())->toArray(), 'pid');
        $this->navigationlist = $tree->getTreeList($tree->getTreeArray(0), 'name');
        $navigationdata=array();
        $navigationdata[0]='顶级导航';
        if(!empty($this->navigationlist)){
            foreach ($this->navigationlist as $k => $v) {
                $navigationdata[$v['id']] = $v['name'];
            }
        }
        $this->parentlist=$navigationdata;
        $this->view->assign("parentList", $navigationdata);
    }

    public function index(){

        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->order($sort, $order)
                ->count();
            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            foreach ($list as $k => &$v) {
                $v['pid']=$v['pid']?$v['pid'].'-'.$this->parentlist[$v['pid']]:'0-顶级导航';
            }
            unset($v);
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }

        return $this->view->fetch();
    }

    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        return parent::edit($ids);
    }
}
